//
//  GoodsDetailViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/21.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "GoodsDetailViewController.h"
#import "SDCycleScrollView.h"
#import "UIView+Extend.h"
#import "DetailV.h"
#import "ModelView.h"
#import "ParamView.h"
#import "EaseMessageViewController.h"
#import "LoginViewController.h"
#import "ConfirmOrderViewController.h"
#import "CycleModel.h"
#import "OSSHelper.h"
#import "DetailBtnCell.h"
#import "ServicesCell.h"
#import "IntroduceCell.h"
#import "DetailEvaluateView.h"
#import "ShopCartGroup.h"
#import "ShopCartModel.h"
#import "SelectedChatEntryView.h"

@interface GoodsDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;
@property (weak, nonatomic) IBOutlet UILabel *guanzhuLabel; 
@property (weak, nonatomic) IBOutlet UIImageView *guanzhuImageView;
@property (weak, nonatomic) IBOutlet UILabel *hujiaoLabel;
@property (weak, nonatomic) IBOutlet UIImageView *hujiaoImageView;
@property (weak, nonatomic) IBOutlet UIView *guanzhuView;
@property (weak, nonatomic) IBOutlet UIView *hujiaoView;
@property (weak, nonatomic) IBOutlet UIButton *addCartBtn;
@property (weak, nonatomic) IBOutlet UIButton *buyBtn;

@property(nonatomic,assign)BOOL isAddCart;
@property(nonatomic,assign)BOOL isClickPropertyCell;
@property(nonatomic,assign)BOOL isClickPramaCell;


@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)SDCycleScrollView *cycleView;//轮播图
@property(nonatomic,strong)NSMutableArray *picArr;//轮播图oss
@property(nonatomic,strong)NSMutableArray *pathArr;//轮播图本地
@property(nonatomic,strong)DetailV *detailV;
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)ModelView  *modelV;//选择商品属性
@property(nonatomic,strong)UIImageView *mask;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)ParamView *paramView;//详情
@property(nonatomic,strong)DetailEvaluateView *evaluateV;
@property(nonatomic,copy)NSString *propertyName;//属性名称
@property(nonatomic,strong)GoodsDetailModel *model ;
@property(nonatomic,strong)NSArray *listArr;//记录评论的条数用于计算高度
@property(nonatomic,copy)NSString   *introduce;//商品简介
@property(nonatomic,assign)CGFloat introduceRowHeight;
@property(nonatomic,assign)BOOL isSelectedAll;
@property(nonatomic,copy)NSString *p;
@property(nonatomic,copy)NSString *storeName;
@property(nonatomic,copy)NSString *storeId;


@property(nonatomic,strong)SelectedChatEntryView *selectedChatEntryView;
@property(nonatomic,copy)NSString *storeCode;
@property(nonatomic,strong)NSMutableArray *chatOnlineArray;


@end

@implementation GoodsDetailViewController
- (instancetype)init{
    self = [super init];
    if(self){
        [AppDelegate appDealegate].isNeedUpdateFooter = YES;
        //关闭选择商品信息的视图的通知
         [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeAction) name:@"close" object:nil];
       //关闭选择商品信息的视图的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pramaViewClose) name:@"PramaViewClose" object:nil];
        
        //本地路径。创建文件夹
        NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/LunboPhotos"];
        BOOL is= [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
        if(is){
            DLog(@"目录创建成功 ");
        }else{
            DLog(@"目录已存在 ");
        }
        self.pathArr = [NSMutableArray array];
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.modelV){
        [self closeAction];
    }
    if(self.paramView){
        [self pramaViewClose];
    }
    [self removeAllQuickScanLocalImage];
}
//删除本地的快速浏览缓存
-(void)removeAllQuickScanLocalImage{
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/LunboPhotos"];
    BOOL success=   [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
    if(success){
        DLog(@"正在全部删除---删除成功");
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(!ISNOTNEEDMESSAGEBTN){
        self.isNeedMessageItem = YES;
    }
    self.commitBtn.hidden = YES;
    self.vcName = @"商品详情";
    self.chatOnlineArray = [NSMutableArray array];
    self.dataSource = [NSMutableArray array];
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-49-kNaviBarHeight)];
    [self.view  addSubview:_scrollView];
    //轮播图
    [self cyleVIew];
    _detailV =[[[NSBundle mainBundle]loadNibNamed:@"DetailV" owner:self options:nil]lastObject];
    _detailV.top = self.cycleView.bottom;
    _detailV.left = 0;
    [self.scrollView addSubview:_detailV];
    [self tableViewAndHeaderView];
     _scrollView.contentSize = CGSizeMake(Main_Screen_Width, self.cycleView.height+self.tableV.height+self.evaluateV.height);
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view bringSubviewToFront:self.buttonView];
    self.guanzhuLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:14];
    self.hujiaoLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:14];

    //加载详情数据
    [self loadData];
}

-(void)setPid:(NSString *)pid{
    _pid = pid;
}

-(void)initEvaluateView{
    _evaluateV = [[DetailEvaluateView alloc]initWithFrame:CGRectMake(0, self.tableV.bottom, Main_Screen_Width, 0)];
    _evaluateV.pid = self.pid;
    [self.scrollView addSubview:self.evaluateV];
    __weak typeof(self) weakSelf = self;
    _evaluateV.evaluateBlock = ^(int count) {
        [weakSelf getEValuateGoodsWithInt:count];
    };
}

- (void)loadData{
    //2.4 商品详情接口
//    pid;//需要从上个页面传递过来
    NSString *uid ;
    if(USERID.length){
        uid = USERID;
    }else{
        uid = @"";
    }
    NSDictionary *paraDic = @{
                              @"pid":self.pid,
                              @"userId":uid,
                              @"userType":@"0"
                              };
         __weak typeof(self)  weakSelf = self;
   [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:DETAILGOODS paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"商品详情接口----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) {
                [MBProgressHUD dismissHUD];
                return ;
            }
            //storeCode
            weakSelf.storeCode = dataDic[@"storeCode"];
            //发送更新足迹的通知
            [[NSNotificationCenter defaultCenter]postNotificationName:@"updateFooter" object:nil];
            weakSelf.model = [GoodsDetailModel modelWithDic:dataDic];
            weakSelf.detailV.model = weakSelf.model;
            weakSelf.paramView.model = weakSelf.model;
            weakSelf.modelV.goodPic = weakSelf.goodPic;
            weakSelf.modelV.model = weakSelf.model;
            weakSelf.storeName = dataDic[@"storeName"];
            weakSelf.storeId = dataDic[@"storeId"];
                   //商品简介
            if(![dataDic[@"introduce"] isKindOfClass:[NSNull class]]){
                NSString *introduce = dataDic[@"introduce"];
                if(introduce.length){
                    weakSelf.introduce = introduce;
                    ServiceModel *model = [[ServiceModel alloc]init];
                    model.introduce = introduce;
                    [weakSelf.dataSource addObject:model];
                    CGRect frame = [self.introduce boundingRectWithSize:CGSizeMake(Main_Screen_Width-30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
                    weakSelf.introduceRowHeight = CGRectGetHeight(frame)+20;
                    weakSelf.tableV.height += weakSelf.introduceRowHeight;
                }else{
                    weakSelf.introduce = @"";
                }
            }else{
                weakSelf.introduce = @"";
            }

            //显示服务
            NSString *pservice = dataDic[@"pservice"];
            if([pservice isKindOfClass:[NSNull class]]){
                pservice = @"";
            }
            if(pservice.length){
                if([pservice containsString:@"提供发票"]){
                    ServiceModel *model = [[ServiceModel alloc]init];
                    model.name =@"提供发票";
                    model.value = @"本商品提供发票";
                    [weakSelf.dataSource addObject:model];
                    weakSelf.tableV.height +=40;
                }
                if([pservice containsString:@"保修服务"]){
                    ServiceModel *model = [[ServiceModel alloc]init];
                    model.name =@"保修服务";
                    model.value =  @"本商品支持保修服务";
                    [weakSelf.dataSource addObject:model];
                    weakSelf.tableV.height +=40;
                }
                if([pservice containsString:@"送货上门"]){
                    ServiceModel *model = [[ServiceModel alloc]init];
                    model.name =@"送货上门";
                    model.value =  @"本商品单件送货到家";
                    [weakSelf.dataSource addObject:model];
                    weakSelf.tableV.height +=40;
                }
                if([pservice containsString:@"7天无条件退款"]){
                    ServiceModel *model = [[ServiceModel alloc]init];
                    model.name =@"7天无条件退款";
                    model.value =  @"本商品支持7天无条件退款";
                    [weakSelf.dataSource addObject:model];
                    weakSelf.tableV.height +=40;
                }
            }
            //属性名称
            weakSelf.propertyName = dataDic[@"ppropertyname"];
            if(weakSelf.propertyName.length){
                weakSelf.tableV.height +=40;
            }
            NSArray *pramas = dataDic[@"proParam"];
            if(pramas.count){
                weakSelf.tableV.height +=40;
            }
            [weakSelf.tableV reloadData];
            [weakSelf initEvaluateView];
            [weakSelf getEValuateGoodsWithInt:3];

            //---1轮播图数据
            NSArray *pics = dataDic[@"pics"];
            self.picArr = [NSMutableArray array];
            if(pics.count){
                for(NSDictionary *dic in pics){
                    CycleModel *model = [[CycleModel alloc]init];
                    model.pic = dic[@"pic"];
                    model.no =dic[@"no"];
                    [self.picArr addObject:model];
                }
                [self loadIamge];
            }
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
     }];
}

//2.5 获取商品评价接口
- (void)getEValuateGoodsWithInt:(int)count{
    NSString *level = [NSString stringWithFormat:@"%d",count];
    NSDictionary *paraDic = @{
                              @"pid":self.pid,//商品标识
                              @"level":level,//评价等级
                              @"size":@"10",//需要返回的评论最大条数
                              @"currentpage":@"1"
                              };
//    [MBProgressHUD showActivityMessageInWindow:@""];
      __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:EVALUATEGOODS paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取商品评价接口----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            NSArray *list =dataDic[@"contents"];
            if(list.count){
                weakSelf.listArr = dataDic[@"contents"];
                [weakSelf getScrollViewHeight];
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"evaluateResults" object:dataDic];
            }else{
                [weakSelf getScrollViewHeightNonCount];
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
-(void)getScrollViewHeightNonCount{
    self.evaluateV.height=0+83+55*self.listArr.count;
    _scrollView.contentSize = CGSizeMake(Main_Screen_Width, self.cycleView.height+84+self.tableV.height+self.evaluateV.height);
}
-(void)getScrollViewHeight{
    self.evaluateV.height=40+83+55*self.listArr.count;
    _scrollView.contentSize = CGSizeMake(Main_Screen_Width, self.cycleView.height+84+self.tableV.height+self.evaluateV.height);
}

#pragma mark --私信
//私信不是关注
- (IBAction)guanzhu:(UIButton *)sender {
    if(![AppDelegate appDealegate].uid.length){
        LoginViewController *login = [[LoginViewController alloc]init];
        login.isModel = YES;
        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
        [self  presentViewController:baseNavi animated:YES completion:nil];
        return;
    }
    [self showSelectedChatView];
    [self loadChatEntryData];
}
//2.66获取店铺在线员工列表
-(void)loadChatEntryData{
    NSDictionary *paramDic = @{@"storeCode":self.storeCode};
    __weak typeof( self) weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GETONLINEASSISTANTS paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取店铺在线员工列表--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                return ;
            }
            if(self.chatOnlineArray.count){
                [self.chatOnlineArray removeAllObjects];
            }
            for(NSDictionary *dic in listArr){
                ChatEntryModel *model = [ChatEntryModel modelWithDic:dic ];
                [weakSelf.chatOnlineArray addObject:model];
            }
            weakSelf.selectedChatEntryView.dataArray = weakSelf.chatOnlineArray;
        }
    }];
}

- (void)showSelectedChatView{
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.maskV];
    [window addSubview:self.selectedChatEntryView];
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    //关闭入口视图
    _selectedChatEntryView.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.selectedChatEntryView removeFromSuperview];
    };
    //建立会话
    _selectedChatEntryView.creatChatBlock = ^(NSString *userName,NSString *nickName) {
        EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:userName conversationType:EMConversationTypeChat];
        chatController.vcName = nickName;
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.selectedChatEntryView removeFromSuperview];
        [weakSelf.navigationController pushViewController:chatController animated:YES];
    };
}

- (SelectedChatEntryView *)selectedChatEntryView{
    if(_selectedChatEntryView==nil){
        _selectedChatEntryView =[[[NSBundle mainBundle]loadNibNamed:@"SelectedChatEntryView" owner:self options:nil]lastObject];
        _selectedChatEntryView.layer.cornerRadius = 5;
        _selectedChatEntryView.layer.masksToBounds = YES;
        
        _selectedChatEntryView.centerX = Main_Screen_Width/2;
        _selectedChatEntryView.centerY = self.view.centerY;
    }
    return _selectedChatEntryView;
}

#pragma mark --呼叫直播
- (IBAction)callAlive:(UIButton *)sender {
    [MBProgressHUD showTipMessageInWindow:@"该功能正在开发\r\n敬请期待..."];
}


#pragma mark --加入购物车
//加入购物车
- (IBAction)shoppingCart:(UIButton *)sender {
    if(![AppDelegate appDealegate].uid.length){
        LoginViewController *login = [[LoginViewController alloc]init];
        login.isModel = YES;
        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
        [self  presentViewController:baseNavi animated:YES completion:nil];
        return;
    }
    //判断是否是查看属性时加入购物车
    if(self.isClickPropertyCell){
        if(self.p==nil||!self.isSelectedAll){
            [MBProgressHUD showTipMessageInWindow:@"请选择属性"];
            return;
        }
        [self addToCartWithProperty:self.p];
        return;
    }
    //判断是否需要选择属性
    if(self.propertyName.length){
        [self modelAction];//属性
        self.buttonView.hidden = YES;
        self.commitBtn.hidden = NO;
        self.isAddCart = YES;
        return;
    }
    [self addToCartWithProperty:@""];
}

#pragma mark --立即购买
//立即购买
- (IBAction)buy:(UIButton *)sender {
     [MBProgressHUD showTipMessageInWindow:@"该功能正在开发\r\n敬请期待..."];
//    if(![AppDelegate appDealegate].uid.length){
//        LoginViewController *login = [[LoginViewController alloc]init];
//        login.isModel = YES;
//        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
//        [self  presentViewController:baseNavi animated:YES completion:nil];
//        return;
//    }
//    
//    if(self.isClickPropertyCell){
//        if(self.p==nil||!self.isSelectedAll){
//            [MBProgressHUD showTipMessageInWindow:@"请选择属性"];
//            return;
//        }
//         [self buyAtonce];
//        return;
//    }
//
//    if(self.propertyName.length){
//        if(self.isAddCart){
//            self.isAddCart = NO;
//        }
//        [self modelAction];//属性
//        self.commitBtn.hidden = NO;
//        self.buttonView.hidden= YES;
//        return;
//    }
//    [self buyAtonce];
}

#pragma mark --通知调取方法-懒加载视图
//通知调取方法--------懒加载视图---------

- (void)closeAction{
    [self.mask removeFromSuperview];
    [self.modelV removeFromSuperview];
    self.commitBtn.hidden = YES;
    self.buttonView.hidden = NO;
    if(self.isClickPropertyCell){
        self.isClickPropertyCell = NO;
    }
}
-(void)pramaViewClose{
    [self.mask removeFromSuperview];
    [self.paramView removeFromSuperview];
    if(self.isClickPramaCell){
        self.isClickPramaCell = NO;
    }
}

- (void)pramaModelView{
    if(self.isClickPropertyCell){
        [self closeAction];
    }

    CGFloat  heigt = Main_Screen_Height-100-kNaviBarHeight-49;
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.mask];
    [window addSubview:self.paramView];
    [UIView animateWithDuration:.3 animations:^{
        self.paramView.frame = CGRectMake(0, 100+kNaviBarHeight, Main_Screen_Width, heigt);
    }];
}
-(void)setGoodPic:(NSString *)goodPic{
    _goodPic = goodPic;
}
- (void)modelAction{
    if(self.isClickPramaCell){
        [self pramaViewClose];
    }
    CGFloat  heigt = Main_Screen_Height-100-kNaviBarHeight-49;
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.mask];
    [window addSubview:self.modelV];
    
    //返回选择的属性值
    __weak typeof(self) weakSelf = self;
    self.modelV.propertyBlock = ^(NSString *parr,BOOL is) {
        weakSelf.p= parr;
        weakSelf.isSelectedAll = is;
    };

    [UIView animateWithDuration:.3 animations:^{
        self.modelV.frame = CGRectMake(0, 100+kNaviBarHeight, Main_Screen_Width, heigt);
    }];
}

-(ParamView *)paramView{
    if(_paramView==nil){
        _paramView =[[[NSBundle mainBundle]loadNibNamed:@"ParamView" owner:self options:nil]lastObject];
        _paramView.frame = CGRectMake(0, Main_Screen_Height+50, Main_Screen_Width, Main_Screen_Height-100-kNaviBarHeight-49);
    }
    return _paramView;
}

- (UIImageView *)mask{
    if(_mask==nil){
        _mask = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width,Main_Screen_Height-49)];
        _mask.image = [UIImage imageNamed:@"wode_zhezhao"];
        _mask.userInteractionEnabled = YES;
    }
    return _mask;
}
-(ModelView *)modelV{
    if(_modelV==nil){
        _modelV =[[[NSBundle mainBundle]loadNibNamed:@"ModelView" owner:self options:nil]lastObject];
        _modelV.frame = CGRectMake(0, Main_Screen_Height+50, Main_Screen_Width, Main_Screen_Height-100-kNaviBarHeight-49);
    }
    return _modelV;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark --轮播图图片加载
- (void)cyleVIew{
    CGFloat cycleScrollViewScale = 1;
    CGFloat topViewHeight = Main_Screen_Width/cycleScrollViewScale;
    //轮播图
    self.cycleView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, topViewHeight)];
    self.cycleView.currentPageDotImage = [UIImage imageNamed:@"lunbodian_nor"];
    self.cycleView.pageDotImage = [UIImage imageNamed:@"lunbodian_sel"];
    self.cycleView.autoScrollTimeInterval = 4.0;
    [_scrollView addSubview:self.cycleView];
}

//加载轮播图图片
-(void)loadIamge{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for(int i = 0;i<self.picArr.count;i++){
            CycleModel *model = self.picArr[i];
           [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:model.pic xOssProcess:[NSString stringWithFormat:@"image/resize,m_fill,w_%d,h_%d",(int)(Main_Screen_Width),(int)(Main_Screen_Width)]  downLoadBlock:^(NSData *data) {
                //保存到本地
                [weakSelf saveTolocal:data index:i];
            }];
        }
    });
}
-(void)saveTolocal:(NSData*)imageData index:(int)index{
    NSString *imageName ;
    UIImage *image= [UIImage imageWithData:imageData];
    if(UIImagePNGRepresentation(image)){//返回为png图像
        imageName = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    }else{ //返回为JPEG图像
        imageName = [NSString stringWithFormat:@"%@.jpeg",[self getTimeNow]];
    }
    //本地路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/LunboPhotos"];
    //创建文件
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
    BOOL isSuccess= [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:nil];
    if(!isSuccess){
        NSLog(@"失败");
    }
    DLog(@"path---%@",path);
    if(isSuccess){
        //回到主线城刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.pathArr addObject:path];
            if(self.pathArr.count==self.picArr.count){
                self.cycleView.localizationImageNamesGroup = self.pathArr;
                [MBProgressHUD dismissHUD];
            }
        });
    }
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}

#pragma mark  --- 表视图
- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, self.detailV.bottom, Main_Screen_Width, 0) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = DEF_COLOR242;
    _tableV.delegate = self;
    _tableV.dataSource =self;
    _tableV.separatorStyle =UITableViewCellSeparatorStyleNone;
    [self.scrollView addSubview:_tableV];
//    _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.scrollEnabled = NO;
}
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.propertyName.length){
        return self.dataSource.count+2;
    }
    return self.dataSource.count+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row>=self.dataSource.count){
        NSString *ident=@"DetailBtnCell";
        DetailBtnCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
        if(cell==nil){
            cell=[[[NSBundle mainBundle]loadNibNamed:@"DetailBtnCell" owner:self options:nil]lastObject];
        }
        if(self.propertyName.length){
            if(indexPath.row==self.dataSource.count){
        //                cell.nameLabel.text = self.propertyName;
                cell.nameLabel.text = @"商品属性";
            }
            if(indexPath.row==self.dataSource.count+1){
                cell.nameLabel.text = @"参数详情";
            }
        }else{
            if(indexPath.row==self.dataSource.count){
                cell.nameLabel.text = @"参数详情";
            }
        }
        return cell;
    }
    if(self.introduce.length&&indexPath.row==0){
        IntroduceCell *cell =[[[NSBundle mainBundle]loadNibNamed:@"IntroduceCell" owner:self options:nil]lastObject];
        cell.model = self.dataSource[indexPath.row];
        return cell;
    }
    NSString *ident=@"ServicesCell";
    ServicesCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"ServicesCell" owner:self options:nil]lastObject];
    }
    ServiceModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.introduce.length&&indexPath.row==0){
//        CGRect frame = [self.introduce boundingRectWithSize:CGSizeMake(Main_Screen_Width-30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
//        CGFloat height = CGRectGetHeight(frame)+20;
        return self.introduceRowHeight;
    }
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.propertyName.length){
        if(indexPath.row==self.dataSource.count){
            self.isClickPropertyCell = YES;
            [self modelAction];//属性
        }
        if(indexPath.row==self.dataSource.count+1){
            self.isClickPramaCell = YES;
            [self pramaModelView];//参数
        }
    }else{
        if(indexPath.row==self.dataSource.count){
            self.isClickPramaCell = YES;
            [self pramaModelView];//参数
        }
    }
}
//确定按钮
- (IBAction)commit:(UIButton *)sender {
    if(self.p==nil||!self.isSelectedAll){
        [MBProgressHUD showTipMessageInWindow:@"请选择属性"];
        return;
    }

    if(self.isAddCart){//添加购物车
        [self addToCartWithProperty:self.p];
    }else{//立即购买
        [self buyAtonce];
    }
}


//立即购买
-(void)buyAtonce{
    if(self.isClickPropertyCell){
        self.isClickPropertyCell = NO;
    }
    if(self.propertyName.length){//跳转的时候关闭属性视图
        [self closeAction];
    }
    ConfirmOrderViewController *confimOrderVC = [[ConfirmOrderViewController alloc]init];
    ShopCartGroup *group = [[ShopCartGroup alloc]init];
    group.storeId  = self.storeId;
    group.storeName = self.storeName;
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1];
    ShopCartModel *model = [[ShopCartModel alloc]init];
    model.name = _smodel.goodsName;
    model.pPrice =[NSString stringWithFormat:@"￥ %@",_smodel.price];
    model.pId = _smodel.id;
    model.pPic = _smodel.imageName;
    model.pProperty = self.p;
    model.goodsCount = 1;
    [arr addObject:model];
    group.shopCartModels = arr;
    NSMutableArray *dataSource = [NSMutableArray arrayWithObject:group];
    confimOrderVC.dataSource = dataSource;
    confimOrderVC.totalMoney = _smodel.price;
    [self.navigationController pushViewController:confimOrderVC animated:YES];
}

//-(void)setSmodel:(StoreModel *)smodel{
//    _smodel = smodel;
//}
-(void)addToCartWithProperty:(NSString*)property{
    //2.28用户添加商品到购物车
    NSDictionary *paramDic = @{@"productId":self.pid,@"uid":USERID,@"property":property};
    DLog(@"--加购物车参数----%@",paramDic);
    [Tools AFNetworkingRequestTypePostWithUrl:ADDCART paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"用户添加商品到购物车---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]])return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){//
                [MBProgressHUD showTipMessageInWindow:@"添加成功"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(self.isClickPropertyCell){
                        self.isClickPropertyCell = NO;
                    }
                    [self.addCartBtn setImage:[UIImage imageNamed:@"shangpinxiangqing-_gouwuche_sel"] forState:UIControlStateNormal];
                    if(self.propertyName.length){//有的有属性有的没有属性
                        [self closeAction];
                    }
                });
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
